package me.nereo.multi_image_selector.utils;

import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;

/**
 * 将保存的资源扫描到媒体库.
 */
public class MediaSave {

    public static final String JPG_MIME = "image/jpeg";

    private Context mContext;
    private static MediaSave saver = null;

    private MediaSave(Context context) {
        mContext = context;
    }

    public static MediaSave getInstance(Context context) {
        if (saver == null) saver = new MediaSave(context);
        return saver;
    }

    /**
     * 在4.4及以上用MediaScannerConnection扫描
     * 在之下用广播扫描
     */
    public void scanJPG(String path) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            scanFiles(path, JPG_MIME);
        } else {
            mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
        }
    }

    public void scanFiles(String filePath, String mimeType) {
        MediaScanner mediaScanner = new MediaScanner(mContext);
        mediaScanner.scanFiles(filePath, mimeType);
    }

    class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
        private MediaScannerConnection conn = null;
        private String path, mimeType;

        public MediaScanner(Context context) {
            conn = new MediaScannerConnection(context, this);
        }

        public void scanFiles(String path, String mimeType) {
            this.mimeType = mimeType;
            this.path = path;
            conn.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            conn.scanFile(path, mimeType);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            conn.disconnect();
        }
    }


}
